package com.pubinfo.passbook.data.quartz.utils;

import org.quartz.CronExpression;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CronExprUtil {
  
  /**
   * @param cronExpr cron 表达式
   * @Description: 校验cron 表达式格式是否正确
   * @return: true/false
   * @author: zongf
   * @time: 2019-04-10 10:48:11
   */
  public static boolean isCronRight(String cronExpr) {
    if (cronExpr == null || cronExpr.trim().isEmpty()) {
      return false;
    }
    try {
      new CronExpression(cronExpr);
      
    } catch (ParseException e) {
      // 非法表达式会抛出异常: ParseException
      return false;
    }
    return false;
  }
  
  /**
   * @param cron cron表达式
   * @Description: 输出
   * @author: zongf
   * @time: 2019-04-10 12:39:02
   */
  public static void mockTrigger(String cron, int times) {
    try {
      
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      
      CronExpression cronExpr = new CronExpression(cron);
      
      int triggerTimes = 1;
      
      // 初始化上次执触发时间为当前时间
      Date lastedTriggeredTime = new Date();
      
      while (true && triggerTimes <= times) {
        
        // 获取下次触发时间
        Date nextInvokeTime = cronExpr.getNextValidTimeAfter(lastedTriggeredTime);
        System.out.printf("第%2d次触发时间:%s\n", triggerTimes, sdf.format(nextInvokeTime));
        
        // 重置上次触发时间
        lastedTriggeredTime = cronExpr.getNextInvalidTimeAfter(nextInvokeTime);
        
        // 触发次数自增1
        triggerTimes++;
      }
      
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

